package com.coursebooking.controller;

import com.baomidou.mybatisplus.annotation.TableField;
import com.coursebooking.model.Teacher;
import com.coursebooking.model.User;
import com.coursebooking.service.TeacherService;
import com.coursebooking.service.UserService;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/teachers")
@CrossOrigin(origins = "*")
public class TeacherController {

    @Autowired
    private TeacherService teacherService;
    @Autowired
    private UserService userService;

    @GetMapping
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<List<Teacher>> getAllTeachers() {
        List<Teacher> teachers = teacherService.findAll();
        return ResponseEntity.ok(teachers);
    }

    @GetMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN') or hasRole('TEACHER')")
    public ResponseEntity<Teacher> getTeacherById(@PathVariable Long id) {
        Optional<Teacher> teacher = teacherService.findById(id);
        return teacher.map(ResponseEntity::ok).orElse(ResponseEntity.notFound().build());
    }

    @PostMapping
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> createTeacher(@RequestBody  TeacherRequest teacherRequest) {
        try {
            if (teacherService.existsByEmail(teacherRequest.getEmail())) {
                return ResponseEntity.badRequest().body(new MessageResponse("邮箱已存在"));
            }
            if (teacherRequest.getUsername() == null || teacherRequest.getUsername().isEmpty()){
                return ResponseEntity.badRequest().body(new MessageResponse("用户名不能为空"));
            }
            if (teacherRequest.getPassword() == null || teacherRequest.getPassword().isEmpty()){
                return ResponseEntity.badRequest().body(new MessageResponse("密码不能为空"));
            }

            if (userService.existsByUsername(teacherRequest.getUsername())){
                return ResponseEntity.badRequest().body(new MessageResponse("用户名已存在"));
            }

            Teacher teacher = new Teacher();
            BeanUtils.copyProperties(teacherRequest, teacher);
            teacherService.save(teacher);

            userService.createUser(teacherRequest.getUsername(), teacherRequest.getPassword(), teacher.getEmail(), User.Role.TEACHER, teacher.getId());
            return ResponseEntity.ok(teacher);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(new MessageResponse("创建教师失败: " + e.getMessage()));
        }
    }

    @PutMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN') or hasRole('TEACHER')")
    public ResponseEntity<?> updateTeacher(@PathVariable Long id, @RequestBody Teacher teacher) {
        try {
            if (!teacherService.existsById(id)) {
                return ResponseEntity.notFound().build();
            }
            //Teacher Teacher = new Teacher();
            //teacher.setId(id);
            //teacher.setName(teacherRequest.getName());
            //teacher.setEmail(teacherRequest.getEmail());
            //teacher.setPhone(teacherRequest.getPhone());
            //teacher.setDepartment(teacherRequest.getDepartment());
            teacher.setId(id);

            Teacher entity = teacherService.updateTeacher(teacher);

            return ResponseEntity.ok(entity);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(new MessageResponse("更新教师信息失败: " + e.getMessage()));
        }
    }

    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> deleteTeacher(@PathVariable Long id) {
        try {
            teacherService.deleteTeacher(id);
            return ResponseEntity.ok(new MessageResponse("教师删除成功"));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(new MessageResponse("删除教师失败: " + e.getMessage()));
        }
    }

    @GetMapping("/email/{email}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<Teacher> getTeacherByEmail(@PathVariable String email) {
        Optional<Teacher> teacher = teacherService.findByEmail(email);
        return teacher.map(ResponseEntity::ok).orElse(ResponseEntity.notFound().build());
    }

    @GetMapping("/check/email/{email}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<ExistsResponse> checkEmailExists(@PathVariable String email) {
        boolean exists = teacherService.existsByEmail(email);
        return ResponseEntity.ok(new ExistsResponse(exists));
    }

    // 内部类定义
    public static class TeacherRequest {
        private String name;
        private String email;
        private String phone;
        private String department;
        private String gender; // ENUM: 'MALE', 'FEMALE'

        private String title; // ENUM: '教授', '副教授', '讲师', '助教'

        @JsonFormat(pattern = "yyyy-MM-dd")
        private Date birthDate; // 出生日期

        @JsonFormat(pattern = "yyyy-MM-dd")
        private Date hireDate; // 入职时间

        private String address; // 地址

        private String bio; // 个人简介 (TEXT)

        private String username;
        private String password;

        public String getGender() {
            return gender;
        }

        public void setGender(String gender) {
            this.gender = gender;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public Date getBirthDate() {
            return birthDate;
        }

        public void setBirthDate(Date birthDate) {
            this.birthDate = birthDate;
        }

        public Date getHireDate() {
            return hireDate;
        }

        public void setHireDate(Date hireDate) {
            this.hireDate = hireDate;
        }

        public String getAddress() {
            return address;
        }

        public void setAddress(String address) {
            this.address = address;
        }

        public String getBio() {
            return bio;
        }

        public void setBio(String bio) {
            this.bio = bio;
        }

        public String getUsername() {
            return username;
        }

        public void setUsername(String username) {
            this.username = username;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }

        public String getName() { return name; }
        public void setName(String name) { this.name = name; }
        public String getEmail() { return email; }
        public void setEmail(String email) { this.email = email; }
        public String getPhone() { return phone; }
        public void setPhone(String phone) { this.phone = phone; }
        public String getDepartment() { return department; }
        public void setDepartment(String department) { this.department = department; }
    }

    public static class MessageResponse {
        private String message;

        public MessageResponse(String message) {
            this.message = message;
        }

        public String getMessage() { return message; }
        public void setMessage(String message) { this.message = message; }
    }

    public static class ExistsResponse {
        private boolean exists;

        public ExistsResponse(boolean exists) {
            this.exists = exists;
        }

        public boolean isExists() { return exists; }
        public void setExists(boolean exists) { this.exists = exists; }
    }
}